import React, { Component } from 'react'
import { Button } from 'antd'

export default class CustomSetState extends Component {
  state = {
    data: {
      count: 0,
      baseNum: 1
    }
  }
  handleClick = (type) => {
    return () => {
      switch (type) {
        case 'increment_baseNum':
          this.setState({ data: { ...this.state.data, baseNum: this.state.data.baseNum + 1 } }) //写法一：语法糖，直接写修改的对象
          console.log('同步代码只能拿到旧值：', this.state.data.baseNum);
          break;
        case 'decrement_baseNum':
          this.setState({ data: { ...this.state.data, baseNum: this.state.data.baseNum - 1 } }, () => console.log('回调形式能拿到最新值：', this.state.data.baseNum))
          break;
        case 'incrment_count':
          this.incrmentCount() //写法二：函数式调用，返回值为 修改的对象，并用async 和 await，以同步代码拿到最新值
          break;
        case 'decrment_count':
          this.setState(state => ({ data: { ...state.data, count: state.data.count - state.data.baseNum } }), () => console.log('回调形式能拿到最新值：', this.state.data.count))
          break;
        default:
          break;
      }
    }
  }

  incrmentCount = async () => {
    await this.setState(state => ({ data: { ...state.data, count: state.data.count + state.data.baseNum } }))
    console.log('用async和await拿到最新值', this.state.data.count);
  }

  render() {
    const { count, baseNum } = this.state.data

    return (
      <div>
        <h1>setState的两种用法</h1>
        <h3>当前基数：{baseNum}</h3>
        <h3>当前结果：{count}</h3>
        <Button onClick={this.handleClick('incrment_count')}>结果加</Button>
        <Button onClick={this.handleClick('decrment_count')}>结果减</Button>
        &nbsp;
        <Button onClick={this.handleClick('increment_baseNum')}>基数加</Button>
        <Button onClick={this.handleClick('decrement_baseNum')}>基数减</Button>
      </div>
    )
  }
}
